﻿Shader "ReflectionMap"
{
    Properties
    {
        _ReflectionMap("SkyBox", CUBE) = "black"{}
        _Glossiness ("Smoothness", Range(0, 1)) = 0.5
    }
    SubShader
    {
        
        Tags
        { 
            "RenderPipeline"="UniversalRenderPipeline"
            "LightMode"="UniversalForward"
            "RenderType"="Opaque"
        }
        LOD 100

        HLSLINCLUDE
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" 
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

        samplerCUBE _ReflectionMap;

        CBUFFER_START(UnityPerMaterial)
        half4 _MainColor;
        float _Glossiness; 
        CBUFFER_END

        struct a2v
        {
            float4 positionOS : POSITION;
            float3 normalOS : NORMAL;
            float2 texcoord : TEXCOORD;
        };
        struct v2f
        {
            float4 positionCS : SV_POSITION;
            half3 normalWS : NORMAL;
            half3 positionWS : TEXCOORD0;
        };
        ENDHLSL
        
        pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            v2f vert(a2v v)
            {
                v2f o;
                o.positionCS = TransformObjectToHClip(v.positionOS.xyz);
                o.positionWS = TransformObjectToWorld(v.positionOS.xyz);
                o.normalWS =TransformObjectToWorldNormal(v.normalOS.xyz);
                return o;
            }

            half4 frag(v2f i):SV_Target
            {
                half3 normalWS = normalize(i.normalWS);
                half3 viewDir = normalize(GetCameraPositionWS() - i.positionWS);
                half3 reflectDir = normalize(reflect(-viewDir,normalWS));
                half3 skyBox = texCUBElod(_ReflectionMap, half4(reflectDir, _Glossiness* 5)).rgb;
                return half4(skyBox, 1);
            }
            ENDHLSL
        }
    }
}